# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: inkyu

import coin.proto.coin_market_enums_pb2 as coin_enum
import coin.proto.coin_order_enums_pb2 as coin_order
from coin.exchange.base.order_gateway_logger import OrderGatewayLogProvider
from coin.proto.coin_order_gateway_pb2 import OrderEvent
from coin.exchange.base.order_gateway_log_builder import (
    prepare_builder,
    BaseOrderEventBuilder,
)


class UpbitOrderGatewayLogProvider(OrderGatewayLogProvider):
  exchange_type = coin_enum.Upbit

  def gen_order_event_and_log(self,
                              order,
                              timestamp,
                              order_event_type,
                              filled_qty=None,
                              guess_fill_type=None):
    builder = prepare_builder(BaseOrderEventBuilder,
                              None,
                              timestamp,
                              self.get_next_order_event_id(),
                              self.exchange_type,
                              order.product.symbol)
    builder.set_order(order, str(order.internal.exchange_order_id))

    if order_event_type == OrderEvent.ORDER_ACCEPTED:
      order_state = coin_order.WORKING_ORDER
    elif order_event_type == OrderEvent.ORDER_FILLED:
      assert filled_qty is not None
      if order.internal.fill.fully_filled:
        order_state = coin_order.DEAD_ORDER
      else:
        order_state = coin_order.WORKING_ORDER
      builder.set_fill(order.price, filled_qty, guess_fill_type=guess_fill_type)
    elif order_event_type == OrderEvent.CANCEL_ACCEPTED:
      order_state = coin_order.WORKING_ORDER
    elif order_event_type == OrderEvent.CANCEL_CONFIRMED:
      order_state = coin_order.DEAD_ORDER
    elif order_event_type == OrderEvent.CANCEL_ERROR:
      order_state = coin_order.DEAD_ORDER
    elif order_event_type == OrderEvent.ORDER_REJECTED:
      order_state = coin_order.DEAD_ORDER
    else:
      raise NotImplementedError()

    builder.set_state(order_event_type=order_event_type,
                      order_state=order_state,
                      order_event_source=OrderEvent.EXCHANGE)
    self.write_order_event(builder.oe)
